package ltd.dujiabao.reserver.util;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicNameValuePair;

/**
 * @author : DuJiabao
 * @Project : reserver
 * @Time : 2021/11/4 23:17
 * @Desc : 通过HttpClient发请求
 */


public class HttpClientUtils {
    /**
     * 发送post请求
     *
     * @param url        url
     * @param headers    请求头
     * @param httpEntity 请求体
     * @return 响应对象
     */
    public static HttpResponse doPost(String url, Map<String, String> headers, HttpEntity httpEntity) {
        HttpPost httpPost = new HttpPost(url);
        if (headers != null) {
            headers.forEach(httpPost::setHeader);
        }
        if (httpEntity != null) {
            httpPost.setEntity(httpEntity);
        }
        return doRequest(httpPost);
    }

    /**
     * 会发一个application/x-www-form-urlencoded类型的请求
     *
     * @param url     url
     * @param headers 请求头
     * @param data    key-value数据，放进请求体中
     * @param charset 编码格式
     * @return 响应对象
     */
    public static HttpResponse doPost(String url, Map<String, String> headers, Map<String, String> data, Charset charset) {
        UrlEncodedFormEntity entity = null;
        //设置参数
        List<NameValuePair> list = new ArrayList<>();
        if (data != null) {
            for (Entry<String, String> elem : data.entrySet()) {
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                entity = new UrlEncodedFormEntity(list, charset);
            }
        }

        return doPost(url, headers, entity);
    }

    /**
     * @param url     url
     * @param headers 请求头
     * @return 响应对象
     */
    public static HttpResponse doGet(String url, Map<String, String> headers) {
        HttpGet httpGet = new HttpGet(url);
        if (headers != null) {
            headers.forEach(httpGet::setHeader);
        }
        return doRequest(httpGet);
    }

    /**
     * 发送请求，如果出现异常，就返回空结果
     */
    public static HttpResponse doRequest(HttpUriRequest request) {
        HttpClient httpClient = null;
        try {
            httpClient = new SSLClient();
            return httpClient.execute(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
